<template>
  <el-row>
      <el-col>
          <el-select v-model="state.selected" class="m-2" placeholder="Select" 
          filterable
          @change="change"
          size="large">
              <el-option v-for="item in state.options" :key="item" :label="item" :value="item" />
          </el-select>
      </el-col>
  </el-row>
  <el-row :gutter="20">
    <el-input v-model="searchInput" class="w-50 m-2" 
    @input="searchEvent(searchInput)"
    placeholder="Type something" :prefix-icon="Search" />
  </el-row>

  <el-scrollbar height="600px">
    <p v-for="(item, index) in state.stocksFilterd" :key="index" 
    @click="searchOption(item.stock)"
    class="scrollbar-demo-item">{{ item.stock }}  {{ item.rank }}</p>
  </el-scrollbar>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { Search } from '@element-plus/icons-vue'
import { weekStockSearch } from '../stores/week'
import { storeToRefs } from 'pinia';
import router from '../router'
import { getStocks } from '../service/stock';
import { useRouteQuery } from '../utils/useRoute';

const stockSearchStore = weekStockSearch()
let { input } = storeToRefs(stockSearchStore)

const searchInput  = ref('')
const state = reactive({
  stocks: [],
  selected: "ALL",
  options: ["ALL","30W_UP"],
  stocksFilterd: []  // 搜索后的股票
}) 

let stocks = useRouteQuery('stocks', "")

const loadData = () => {
  getStocks(state.selected).then(res => {
    state.options = res.data.options

    state.stocks = res.data.data
    if (stocks) {
      let filter = stocks.split(';')
      state.stocks = state.stocks.filter(item => {
        return filter.includes(item.stock)
      })
    }

    state.stocksFilterd = state.stocks
  })
}

loadData()


// 点击事件
const searchOption = (stock) => {
  input.value = stock

  let op = {}
  op.stock = stock
  if (stocks) {
    op.stocks = stocks
  }

  router.push({path: "/weekDetail",query: op})
}

const searchEvent = (input) => {
  if (input == '') {
    state.stocksFilterd = state.stocks
    return 0
  }

  let arr = []
  for (let stock of state.stocks) {
    if(stock.stock.includes(input)) {
      arr.push(stock)
    }
    state.stocksFilterd = arr
  }
}

  const change = () => {
    loadData()
  }
</script>

  
<style scoped>
.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}
</style>